﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using KeaoBase;
using KeaoMDS.InfoManage;
using System.Net.Sockets;
using System.Net;
using KeaoMDS.AppCode;

namespace KeaoMDS.Weight
{
    public partial class ChengZhongTuiKu : BaseForm
    {

        private CheLiangPaiHao m_CheLiangPaiHao = new CheLiangPaiHao();
        private string m_ChengZhongLeiXing = string.Empty;//称重类型
        private string m_DangQianWuLiaoMingCheng = string.Empty;//当前物料名称
        private Socket m_Socket = null;
        private byte[] m_SocketReadBytes = new byte[1024];
        private int m_YiBiaoDuShu = 0;
        private bool m_WenDing = false;
        private decimal m_BeiChuShu = Convert.ToDecimal(KeaoUtils.ConfigGetNodeAttr("称重设备", "被除数"));
        private decimal m_DangQianZhongLiang = 0m;//当前重量
        private DataGridViewRow m_Row;//原车退库
        private string  m_CurrentID = string.Empty;//当前编辑信息
        private string m_CurrentBianHao = string.Empty;//当前称重编号

        private DataGridViewRow m_EditRow;//修改退库信息

        public ChengZhongTuiKu()
        {
            InitializeComponent();
        }

        public ChengZhongTuiKu(DataGridViewRow Row,string ChengZhongLeiXing)
        {
            m_Row = Row;
            m_ChengZhongLeiXing = ChengZhongLeiXing;
            InitializeComponent();
        }

        public ChengZhongTuiKu(string ChengZHongLeiXing,DataGridViewRow Row)
        {
            m_EditRow = Row;
            m_ChengZhongLeiXing = ChengZHongLeiXing;
            InitializeComponent();
        }

        private void ChengZhongTuiKu_Load(object sender, EventArgs e)
        {
            dataGridView1.AutoGenerateColumns = false;
            dataGridView2.AutoGenerateColumns = false;
            dataGridView3.AutoGenerateColumns = false;
            dataGridView4.AutoGenerateColumns = false;
            if (!KeaoUtils._CurrentUserRow["juesequanxian"].ToString().Contains("重量调整"))
            {
                txt_maozhong.ReadOnly = true;
                txt_pizhong.ReadOnly = true;
            }
         
            try
            {
                m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                m_Socket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8888));
                m_Socket.BeginReceive(m_SocketReadBytes, 0, 1024, SocketFlags.None, OnReadSocketBytes, 0);

                Tmr_UI.Enabled = true;
            }
            catch (SocketException)
            {
                KeaoUtils.ShowInfoMessage("仪表服务未连接，请检查重试。");
            }

            BindWuLiao();

            if (m_Row != null)
            {
                if (m_ChengZhongLeiXing == "入库物料")
                {
                    txt_pizhong.Text = string.Format("{0}", m_Row.Cells["yiwancheng_ruku_pizhong"].Value);
                    DataTable wuLiaoDt = cmb_wuliao.DataSource as DataTable;
                    foreach (DataRow row in wuLiaoDt.Rows)
                    {
                        if (row["wuliaoleixing"].Equals("入库物料"))
                        {
                            if (row["wuliaomingcheng"].Equals(m_Row.Cells["yiwancheng_ruku_wuliaomingcheng"].Value))
                            {
                                cmb_wuliao.SelectedValue = row["id"];
                            }
                        }
                    }
                    cmb_xinghao.Text=string.Format("{0}", m_Row.Cells["yiwancheng_ruku_xinghao"].Value);
                    cmb_danweimingcheng.Text= string.Format("{0}", m_Row.Cells["yiwancheng_ruku_danweimingcheng"].Value);
                    txt_chepaihao.Text = string.Format("{0}", m_Row.Cells["yiwancheng_ruku_chepaihao"].Value);
               
                }
                else
                {
                    txt_pizhong.Text = string.Format("{0}", m_Row.Cells["yiwancheng_chuku_pizhong"].Value);
                    DataTable wuLiaoDt = cmb_wuliao.DataSource as DataTable;
                    foreach (DataRow row in wuLiaoDt.Rows)
                    {
                        if (row["wuliaoleixing"].Equals("出库物料"))
                        {
                            if (row["wuliaomingcheng"].Equals(m_Row.Cells["yiwancheng_chuku_wuliaomingcheng"].Value))
                            {
                                cmb_wuliao.SelectedValue = row["id"];
                            }
                        }
                    }
                    cmb_xinghao.Text=string.Format("{0}", m_Row.Cells["yiwancheng_chuku_xinghao"].Value);
                    cmb_danweimingcheng.Text=string.Format("{0}", m_Row.Cells["yiwancheng_chuku_danweimingcheng"].Value);
                    txt_chepaihao.Text = string.Format("{0}", m_Row.Cells["yiwancheng_chuku_chepaihao"].Value);
                }

                txt_chepaihao.Enabled = false;
                btn_chepaihao.Enabled = false;
            }

            if (m_EditRow != null)
            {
                txt_maozhong.Text = string.Format("{0}", m_EditRow.Cells["tuikumaozhong"].Value);
                txt_pizhong.Text = string.Format("{0}", m_EditRow.Cells["tuikupizhong"].Value);
                txt_jingzhong.Text = string.Format("{0}", m_EditRow.Cells["tuikujingzhong"].Value);
                DataTable wuLiaoDt = cmb_wuliao.DataSource as DataTable;
                foreach (DataRow row in wuLiaoDt.Rows)
                {
                    if (row["wuliaoleixing"].Equals(m_ChengZhongLeiXing))
                    {
                        if (row["wuliaomingcheng"].Equals(m_EditRow.Cells["tuikuwuliao"].Value))
                        {
                            cmb_wuliao.SelectedValue = row["id"];
                        }
                    }
                }
                cmb_xinghao.Text = string.Format("{0}", m_EditRow.Cells["tuikuxinghao"].Value);
                cmb_danweimingcheng.Text = string.Format("{0}", m_EditRow.Cells["tuikudanwei"].Value);
                txt_chepaihao.Text = string.Format("{0}", m_EditRow.Cells["tuikuchepaihao"].Value);
                m_CurrentID = string.Format("{0}", m_EditRow.Cells["id"].Value);
                txt_beizhu.Text = string.Format("{0}", m_EditRow.Cells["tuikubeizhu"].Value);
            }

            BindInfo();
        }

        private void OnReadSocketBytes(IAsyncResult Args)
        {
            try
            {
                m_Socket.EndReceive(Args);
                m_YiBiaoDuShu = BitConverter.ToInt32(m_SocketReadBytes, 0);
                if (m_SocketReadBytes[4] == 0x01)
                {
                    m_WenDing = false;
                }
                else
                {
                    m_WenDing = true;
                }

                while (true)
                {
                    m_Socket.Receive(m_SocketReadBytes, 0, m_SocketReadBytes.Length, SocketFlags.None);
                    m_YiBiaoDuShu = BitConverter.ToInt32(m_SocketReadBytes, 0);
                    if (m_SocketReadBytes[4] == 0x01)
                    {
                        m_WenDing = false;
                    }
                    else
                    {
                        m_WenDing = true;
                    }
                }
            }
            catch (Exception)
            {
                return;
            }
        }


        #region 物料

        private void BindWuLiao()
        {
            try
            {
                Dictionary<string, string> orderDic = new Dictionary<string, string>();
                orderDic.Add("wuliaoleixing", "asc");
                string createCondition = KeaoUtils._DB.CreateAndCondition("wuliaozhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
                DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_wuliao", createCondition, orderDic);
                foreach (DataRow row in Dt.Rows)
                {
                    row["shangchuanzhuangtai"] = string.Format("{0}   |   {1}", row["wuliaoleixing"], row["wuliaomingcheng"]);
                }
                DataRow newRow = Dt.NewRow();
                newRow["id"] = "";
                newRow["shangchuanzhuangtai"] = "—请选择—";
                Dt.Rows.InsertAt(newRow, 0);
                cmb_wuliao.DisplayMember = "shangchuanzhuangtai";
                cmb_wuliao.ValueMember = "id";
                cmb_wuliao.DataSource = Dt;
            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("绑定物料信息异常。{0}", err.Message));
            }

        }

        private void cmb_wuliao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (cmb_wuliao.SelectedValue.Equals(""))
                {
                    cmb_xinghao.DataSource = null;
                    txt_chepaihao.DataSource = null;
                    cmb_danweimingcheng.DataSource = null;
                    return;
                }
                DataTable wuLiaoDt = cmb_wuliao.DataSource as DataTable;
                DataRow[] selectRows = wuLiaoDt.Select(string.Format("id='{0}'", cmb_wuliao.SelectedValue));
                m_ChengZhongLeiXing = string.Format("{0}", selectRows[0]["wuliaoleixing"]);
                m_DangQianWuLiaoMingCheng = string.Format("{0}", selectRows[0]["wuliaomingcheng"]);
                BindXingHao();
                BindCheLiang();
            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("选定物料异常。{0}", err.Message));
            }
        }

        private void BindXingHao()
        {
            try
            {
                string createCondition = KeaoUtils._DB.CreateAndCondition("wuliaobianhao", DataValueCommonType.字符串, string.Format("{0}", cmb_wuliao.SelectedValue), "", SearchConditionType.等于);
                DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_xinghao", createCondition);
                cmb_xinghao.DisplayMember = "xinghao";
                cmb_xinghao.ValueMember = "id";
                cmb_xinghao.DataSource = Dt;
            }
            catch (Exception err)
            {
                KeaoUtils.LogTxt(string.Format("绑定型号信息异常。{0}", err.Message));
            }
        }

        #endregion

        #region 单位信息

        private void BindDanWei()
        {
            if (m_ChengZhongLeiXing == "入库物料")
            {
                string createCondition = KeaoUtils._DB.CreateAndCondition("danweileixing", DataValueCommonType.字符串, "入库单位", "", SearchConditionType.等于);
                createCondition += KeaoUtils._DB.CreateAndCondition("danweizhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
                DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_danwei", createCondition);
                cmb_danweimingcheng.DisplayMember = "danweimingcheng";
                cmb_danweimingcheng.ValueMember = "id";
                cmb_danweimingcheng.DataSource = Dt;
            }
            else
            {
                string createCondition = KeaoUtils._DB.CreateAndCondition("danweileixing", DataValueCommonType.字符串, "出库单位", "", SearchConditionType.等于);
                createCondition += KeaoUtils._DB.CreateAndCondition("danweizhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
                DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_danwei", createCondition);
                cmb_danweimingcheng.DisplayMember = "danweimingcheng";
                cmb_danweimingcheng.ValueMember = "id";
                cmb_danweimingcheng.DataSource = Dt;
            }
        }


        #endregion

        #region 车辆

        private void btn_chepaihao_Click(object sender, EventArgs e)
        {
            if (m_CheLiangPaiHao.ShowDialog() == DialogResult.OK)
            {
                txt_chepaihao.Text = m_CheLiangPaiHao.m_Current;
            }
        }

        private void BindCheLiang()
        {
            txt_chepaihao.Items.Clear();
            if (m_ChengZhongLeiXing == "入库物料")
            {
                string createCondition = KeaoUtils._DB.CreateAndCondition("cheliangleixing", DataValueCommonType.字符串, "入库车辆", "", SearchConditionType.等于);
                createCondition += KeaoUtils._DB.CreateAndCondition("cheliangzhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
                DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_cheliang", createCondition);
                foreach (DataRow row in Dt.Rows)
                {
                    txt_chepaihao.Items.Add(string.Format("{0}", row["chepaihao"]));
                }

            }
            else
            {
                string createCondition = KeaoUtils._DB.CreateAndCondition("cheliangleixing", DataValueCommonType.字符串, "出库车辆", "", SearchConditionType.等于);
                createCondition += KeaoUtils._DB.CreateAndCondition("cheliangzhuangtai", DataValueCommonType.字符串, "启用", "", SearchConditionType.等于);
                DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_cheliang", createCondition);
                foreach (DataRow row in Dt.Rows)
                {
                    txt_chepaihao.Items.Add(string.Format("{0}", row["chepaihao"]));
                }
            }
        }

        #endregion

        private void Tmr_UI_Tick(object sender, EventArgs e)
        {
            m_DangQianZhongLiang = m_YiBiaoDuShu / m_BeiChuShu;
            u_weight1.SetNumber(m_DangQianZhongLiang.ToString("0.00"),m_WenDing);
        }

        private void btn_maozhong_Click(object sender, EventArgs e)
        {
            txt_maozhong.Text = m_DangQianZhongLiang.ToString("0.00");
        }

        private void btn_pizhong_Click(object sender, EventArgs e)
        {
            txt_pizhong.Text = m_DangQianZhongLiang.ToString("0.00");
        }

        private void txt_maozhong_TextChanged(object sender, EventArgs e)
        {
            if (KeaoUtils.isNumber(txt_maozhong.Text) && KeaoUtils.isNumber(txt_pizhong.Text))
            {
                decimal d = decimal.Parse(txt_maozhong.Text) - decimal.Parse(txt_pizhong.Text);
                txt_jingzhong.Text = d.ToString("0.00");
            }
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            //保存信息
            if (txt_jingzhong.Text == "0.00" || txt_jingzhong.Text == "0")
            {
                KeaoUtils.ShowInfoMessage("重量信息不正确，请检查重试。");
                return;
            }
            if (string.IsNullOrEmpty(cmb_danweimingcheng.Text))
            {
                KeaoUtils.ShowInfoMessage("单位信息不正确，请检查重试。");
                return;
            }
            if (string.IsNullOrEmpty(cmb_wuliao.Text))
            {
                KeaoUtils.ShowInfoMessage("物料信息不正确，请检查重试。");
                return;
            }
            if (string.IsNullOrEmpty(txt_chepaihao.Text))
            {
                KeaoUtils.ShowInfoMessage("车号信息不正确，请检查重试。");
                return;
            }

            if (string.IsNullOrEmpty( m_CurrentID))
            {
                //新增
                TableRow newRow = new TableRow("tbl_tuiku", Guid.NewGuid().ToString(), DBCtl.插入);
                newRow.DataCols.Add(new TableCol() { ColName="tuikumaozhong", ValueMember=txt_maozhong.Text, ValueType= DataValueCommonType.数字 });
                newRow.DataCols.Add(new TableCol() { ColName="tuikupizhong", ValueMember=txt_pizhong.Text, ValueType= DataValueCommonType.数字 });
                newRow.DataCols.Add(new TableCol() { ColName="tuikujingzhong", ValueMember=txt_jingzhong.Text, ValueType= DataValueCommonType.数字 });
                newRow.DataCols.Add(new TableCol() { ColName="tuikuleixing", ValueMember=m_ChengZhongLeiXing,ValueType= DataValueCommonType.字符串 });
                newRow.DataCols.Add(new TableCol() { ColName="tuikuwuliao", ValueMember=m_DangQianWuLiaoMingCheng, ValueType= DataValueCommonType.字符串 });
                newRow.DataCols.Add(new TableCol() { ColName="tuikuxinghao", ValueMember=cmb_xinghao.Text, ValueType= DataValueCommonType.字符串 });
                newRow.DataCols.Add(new TableCol() { ColName="tuikudanwei", ValueMember=cmb_danweimingcheng.Text, ValueType= DataValueCommonType.字符串});
                newRow.DataCols.Add(new TableCol() { ColName="tuikuchepaihao", ValueMember=txt_chepaihao.Text, ValueType= DataValueCommonType.字符串 });
                newRow.DataCols.Add(new TableCol() { ColName="tuikushijian", ValueMember=DateTime.Now, ValueType= DataValueCommonType.日期时间 });
                newRow.DataCols.Add(new TableCol() { ColName="tuikubiaoduan", ValueMember= m_quxiangbiaoduan, ValueType= DataValueCommonType.字符串 });
                newRow.DataCols.Add(new TableCol() { ColName="caozuoyuan", ValueMember=KeaoUtils._CurrentUserRow["yonghuxingming"], ValueType= DataValueCommonType.字符串 });
                if (double.Parse(txt_jingzhong.Text) > 0.00&&double.Parse(txt_pizhong.Text)>0.00&&double.Parse(txt_maozhong.Text)>0.00)
                {
                    newRow.DataCols.Add(new TableCol() { ColName = "shangchuanzhuangtai", ValueMember = "0", ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "tuikubianhao", ValueMember = KeaoUtils.GetSerialNumber(), ValueType = DataValueCommonType.字符串 });
                
                    if (m_ChengZhongLeiXing == "入库物料")
                    {
                        tabControl1.SelectedIndex = 2;
                    }
                    else
                    {
                        tabControl1.SelectedIndex = 3;
                    }
                }
                else
                {
                    newRow.DataCols.Add(new TableCol() { ColName = "shangchuanzhuangtai", ValueMember = "-1", ValueType = DataValueCommonType.字符串 });
                    newRow.DataCols.Add(new TableCol() { ColName = "tuikubianhao", ValueMember = "", ValueType = DataValueCommonType.字符串 });
                
                    if (m_ChengZhongLeiXing == "入库物料")
                    {
                        tabControl1.SelectedIndex = 0;
                    }
                    else
                    {
                        tabControl1.SelectedIndex = 1;
                    }
                }
                newRow.DataCols.Add(new TableCol() { ColName="tuikubeizhu", ValueMember=txt_beizhu.Text, ValueType= DataValueCommonType.字符串 });
                newRow.DataCols.Add(new TableCol() { ColName = "zhandian", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户","站点"), ValueType = DataValueCommonType.字符串 });
                newRow.DataCols.Add(new TableCol() { ColName = "bangfang", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "磅房"), ValueType = DataValueCommonType.字符串 });
                newRow.DataCols.Add(new TableCol() { ColName = "kehubianhao", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "客户编号"), ValueType = DataValueCommonType.字符串 });
                if (KeaoUtils._DB.SaveTableRows(newRow) > 0)
                {
                    BindInfo();
                    button1_Click(null, null);
                    if (tabControl1.SelectedIndex == 2 || tabControl1.SelectedIndex == 3)
                    {
                        KeaoPrinter.PrintTuiKu(newRow.ID);
                    }
                    m_quxiangbiaoduan = string.Empty;
                }
                else
                {
                    KeaoUtils.ShowInfoMessage("保存信息失败，请检查重试...");
                }
            }
            else 
            {
                //修改
               
                TableRow editRow = new TableRow("tbl_tuiku", m_CurrentID, DBCtl.修改);
                editRow.DataCols.Add(new TableCol() { ColName = "tuikumaozhong", ValueMember = txt_maozhong.Text, ValueType = DataValueCommonType.数字 });
                editRow.DataCols.Add(new TableCol() { ColName = "tuikupizhong", ValueMember = txt_pizhong.Text, ValueType = DataValueCommonType.数字 });
                editRow.DataCols.Add(new TableCol() { ColName = "tuikujingzhong", ValueMember = txt_jingzhong.Text, ValueType = DataValueCommonType.数字 });
                editRow.DataCols.Add(new TableCol() { ColName = "tuikuleixing", ValueMember = m_ChengZhongLeiXing, ValueType = DataValueCommonType.字符串 });
                editRow.DataCols.Add(new TableCol() { ColName = "tuikuwuliao", ValueMember = m_DangQianWuLiaoMingCheng, ValueType = DataValueCommonType.字符串 });
                editRow.DataCols.Add(new TableCol() { ColName = "tuikuxinghao", ValueMember = cmb_xinghao.Text, ValueType = DataValueCommonType.字符串 });
                editRow.DataCols.Add(new TableCol() { ColName = "tuikudanwei", ValueMember = cmb_danweimingcheng.Text, ValueType = DataValueCommonType.字符串 });
                editRow.DataCols.Add(new TableCol() { ColName = "tuikuchepaihao", ValueMember = txt_chepaihao.Text, ValueType = DataValueCommonType.字符串 });
                editRow.DataCols.Add(new TableCol() { ColName = "tuikubiaoduan", ValueMember = m_quxiangbiaoduan, ValueType = DataValueCommonType.字符串 });
                editRow.DataCols.Add(new TableCol() { ColName = "caozuoyuan", ValueMember = KeaoUtils._CurrentUserRow["yonghuxingming"], ValueType = DataValueCommonType.字符串 });
                if (double.Parse(txt_jingzhong.Text) > 0.00 && double.Parse(txt_pizhong.Text) > 0.00 && double.Parse(txt_maozhong.Text) > 0.00)
                {
                    editRow.DataCols.Add(new TableCol() { ColName = "shangchuanzhuangtai", ValueMember = "0", ValueType = DataValueCommonType.字符串 });
                    if (string.IsNullOrEmpty(m_CurrentBianHao))
                    {
                        editRow.DataCols.Add(new TableCol() { ColName = "tuikubianhao", ValueMember = KeaoUtils.GetSerialNumber(), ValueType = DataValueCommonType.字符串 });
                    }

                    if (m_ChengZhongLeiXing == "入库物料")
                    {
                        tabControl1.SelectedIndex = 2;
                    }
                    else
                    {
                        tabControl1.SelectedIndex = 3;
                    }
                }
                else
                {
                    editRow.DataCols.Add(new TableCol() { ColName = "shangchuanzhuangtai", ValueMember = "-1", ValueType = DataValueCommonType.字符串 });
                    editRow.DataCols.Add(new TableCol() { ColName = "tuikubianhao", ValueMember = "", ValueType = DataValueCommonType.字符串 });
                    
                    if (m_ChengZhongLeiXing == "入库物料")
                    {
                        tabControl1.SelectedIndex = 0;
                    }
                    else
                    {
                        tabControl1.SelectedIndex = 1;
                    }
                }
                editRow.DataCols.Add(new TableCol() { ColName = "tuikubeizhu", ValueMember = txt_beizhu.Text, ValueType = DataValueCommonType.字符串 });
                editRow.DataCols.Add(new TableCol() { ColName = "zhandian", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "站点"), ValueType = DataValueCommonType.字符串 });
                editRow.DataCols.Add(new TableCol() { ColName = "bangfang", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "磅房"), ValueType = DataValueCommonType.字符串 });
                editRow.DataCols.Add(new TableCol() { ColName = "kehubianhao", ValueMember = KeaoUtils.ConfigGetNodeAttr("客户", "客户编号"), ValueType = DataValueCommonType.字符串 });
                if (KeaoUtils._DB.SaveTableRows(editRow) > 0)
                {
                    BindInfo();
                    button1_Click(null, null);
                    if (tabControl1.SelectedIndex == 2 || tabControl1.SelectedIndex == 3)
                    {
                        KeaoPrinter.PrintTuiKu(editRow.ID);
                    }
                    m_quxiangbiaoduan = string.Empty;
                }
                else
                {
                    KeaoUtils.ShowInfoMessage("保存信息失败，请检查重试...");
                }
            }
            
        }

        private void BindInfo()
        {
            string createCondition = KeaoUtils._DB.CreateAndCondition("shangchuanzhuangtai", DataValueCommonType.字符串, "-1", "", SearchConditionType.等于);
            createCondition += KeaoUtils._DB.CreateAndCondition("tuikuleixing", DataValueCommonType.字符串, "入库物料", "", SearchConditionType.等于);
            Dictionary<string, string> orderBy = new Dictionary<string, string>();
            orderBy.Add("tuikushijian", "desc");
            DataTable ruKuWeiWanChengDt = KeaoUtils._DB.GetDataTableByCondition("tbl_tuiku", createCondition, orderBy);
            dataGridView1.DataSource = ruKuWeiWanChengDt;

            createCondition = KeaoUtils._DB.CreateAndCondition("shangchuanzhuangtai", DataValueCommonType.字符串, "-1", "", SearchConditionType.等于);
            createCondition += KeaoUtils._DB.CreateAndCondition("tuikuleixing", DataValueCommonType.字符串, "出库物料", "", SearchConditionType.等于);
            DataTable chuKuWeiWanChengDt = KeaoUtils._DB.GetDataTableByCondition("tbl_tuiku", createCondition, orderBy);
            dataGridView2.DataSource = chuKuWeiWanChengDt;

            createCondition = KeaoUtils._DB.CreateAndCondition("shangchuanzhuangtai", DataValueCommonType.字符串, "-1", "", SearchConditionType.不等于);
            createCondition += KeaoUtils._DB.CreateAndCondition("tuikuleixing", DataValueCommonType.字符串, "入库物料", "", SearchConditionType.等于);
            createCondition += KeaoUtils._DB.CreateAndCondition("tuikushijian", DataValueCommonType.日期时间, DateTime.Today.ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Today.AddHours(23).AddMinutes(59).AddSeconds(59).ToString("yyyy-MM-dd HH:mm:ss"), SearchConditionType.between);
            DataTable ruKuYiWanChengDt = KeaoUtils._DB.GetDataTableByCondition("tbl_tuiku", createCondition, orderBy);
            if (ruKuYiWanChengDt.Rows.Count > 0)
            {
                DataTable ruKuCount = KeaoUtils._DB.GetDataTableByCondition("tbl_tuiku", "count(id) as cheshu,sum(tuikujingzhong) as tuikujingzhong", null, createCondition, null, null);
                DataRow ruKuCountRow = ruKuYiWanChengDt.NewRow();
                ruKuCountRow["tuikuchepaihao"] = string.Format("合计：{0}车", ruKuCount.Rows[0]["cheshu"]);
                ruKuCountRow["tuikujingzhong"] = ruKuCount.Rows[0]["tuikujingzhong"];
                ruKuYiWanChengDt.Rows.Add(ruKuCountRow);
            }
            dataGridView3.DataSource = ruKuYiWanChengDt;

            createCondition = KeaoUtils._DB.CreateAndCondition("shangchuanzhuangtai", DataValueCommonType.字符串, "-1", "", SearchConditionType.不等于);
            createCondition += KeaoUtils._DB.CreateAndCondition("tuikuleixing", DataValueCommonType.字符串, "出库物料", "", SearchConditionType.等于);
            createCondition += KeaoUtils._DB.CreateAndCondition("tuikushijian", DataValueCommonType.日期时间, DateTime.Today.ToString("yyyy-MM-dd HH:mm:ss"), DateTime.Today.AddHours(23).AddMinutes(59).AddSeconds(59).ToString("yyyy-MM-dd HH:mm:ss"), SearchConditionType.between);
            DataTable chuKuYiWanChengDt = KeaoUtils._DB.GetDataTableByCondition("tbl_tuiku", createCondition, orderBy);
            if (chuKuYiWanChengDt.Rows.Count > 0)
            {
                DataTable chuKuCount = KeaoUtils._DB.GetDataTableByCondition("tbl_tuiku", "count(id) as cheshu,sum(tuikujingzhong) as tuikujingzhong", null, createCondition, null, null);
                DataRow chuKuCountRow = chuKuYiWanChengDt.NewRow();
                chuKuCountRow["tuikuchepaihao"] = string.Format("合计：{0}车", chuKuCount.Rows[0]["cheshu"]);
                chuKuCountRow["tuikujingzhong"] = chuKuCount.Rows[0]["tuikujingzhong"];
                chuKuYiWanChengDt.Rows.Add(chuKuCountRow);
            }
            dataGridView4.DataSource = chuKuYiWanChengDt;

        }

        private void ChengZhongTuiKu_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (m_Socket != null && m_Socket.Connected)
            {
                m_Socket.Shutdown(SocketShutdown.Both);
                m_Socket.Close();
            }
        }

        private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
        }

        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count > 0)
            {
                txt_chepaihao.Text = string.Format("{0}", dataGridView1.SelectedRows[0].Cells["ruku_tuikuchepaihao"].Value);
            }
        }

        private void dataGridView2_DoubleClick(object sender, EventArgs e)
        {
            if (dataGridView2.SelectedRows.Count > 0)
            {
                txt_chepaihao.Text = string.Format("{0}", dataGridView2.SelectedRows[0].Cells["chuku_tuikuchepaihao"].Value);
            }
        }

        private void txt_chepaihao_TextChanged(object sender, EventArgs e)
        {
            string createCondition = KeaoUtils._DB.CreateAndCondition("tuikuchepaihao", DataValueCommonType.字符串, txt_chepaihao.Text, "", SearchConditionType.等于);
            createCondition += KeaoUtils._DB.CreateAndCondition("shangchuanzhuangtai", DataValueCommonType.字符串, "-1", "", SearchConditionType.等于);
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_tuiku", createCondition);
            if (Dt.Rows.Count > 0)
            {
                txt_maozhong.Text = string.Format("{0}", Dt.Rows[0]["tuikumaozhong"]);
                txt_pizhong.Text = string.Format("{0}", Dt.Rows[0]["tuikupizhong"]);
                txt_jingzhong.Text = string.Format("{0}", Dt.Rows[0]["tuikujingzhong"]);
                DataTable wuLiaoDt = cmb_wuliao.DataSource as DataTable;
                foreach (DataRow row in wuLiaoDt.Rows)
                {
                    if (row["wuliaomingcheng"].Equals(Dt.Rows[0]["tuikuwuliao"]) && row["wuliaoleixing"].Equals(Dt.Rows[0]["tuikuleixing"]))
                    {
                        cmb_wuliao.SelectedValue = row["id"];
                    }
                }

                cmb_xinghao.Text = string.Format("{0}", Dt.Rows[0]["tuikuxinghao"]);
                cmb_danweimingcheng.Text = string.Format("{0}", Dt.Rows[0]["tuikudanwei"]);
                txt_beizhu.Text = string.Format("{0}", Dt.Rows[0]["tuikubeizhu"]);
                txt_chepaihao.Text = string.Format("{0}", Dt.Rows[0]["tuikuchepaihao"]);
                m_CurrentID = string.Format("{0}", Dt.Rows[0]["id"]);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            cmb_wuliao.SelectedIndex = 0;
            m_CurrentID = string.Empty;
            txt_beizhu.Text = string.Empty;
            txt_maozhong.Text = "0";
            txt_pizhong.Text = "0";
            txt_jingzhong.Text = "0";
            txt_chepaihao.Text = string.Empty;
            m_CurrentBianHao = string.Empty;

            BindInfo();
        }

        private void menu_2_buda_Click(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 2)
            {
                if (dataGridView3.SelectedRows.Count > 0)
                {
                    string tuiKuID = string.Format("{0}", dataGridView3.SelectedRows[0].Cells["ruku_bianhao_yiwancheng"].Value);
                    if(!string.IsNullOrEmpty(tuiKuID))
                    {
                        KeaoPrinter.PrintTuiKu(tuiKuID);
                    }
                }
            }
            if (tabControl1.SelectedIndex == 3)
            {
                if (dataGridView4.SelectedRows.Count > 0)
                {
                    string tuiKuID = string.Format("{0}", dataGridView4.SelectedRows[0].Cells["chuku_bianhao_yiwancheng"].Value);
                    if (!string.IsNullOrEmpty(tuiKuID))
                    {
                        KeaoPrinter.PrintTuiKu(tuiKuID);
                    }
                }
            }
        }

        private void menu_1_xiugaiweiwancheng_Click(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 0)
            {
                if (dataGridView1.SelectedRows.Count > 0)
                {
                    txt_chepaihao.Text = string.Format("{0}", dataGridView1.SelectedRows[0].Cells["ruku_tuikuchepaihao"].Value);
                }
            }
            if (tabControl1.SelectedIndex == 1)
            {
                if (dataGridView2.SelectedRows.Count > 0)
                {
                    txt_chepaihao.Text = string.Format("{0}", dataGridView2.SelectedRows[0].Cells["chuku_tuikuchepaihao"].Value);
                }
            }
        }

        private void menu_1_shanchuweiwancheng_Click(object sender, EventArgs e)
        {

            if (tabControl1.SelectedIndex == 0)
            {
                if (dataGridView1.SelectedRows.Count > 0)
                {
                    if (KeaoUtils.ShowQuestionMessage("确定要删除入库物资退库信息吗？") == DialogResult.Yes)
                    {
                        string tuiKuID = string.Format("{0}", dataGridView1.SelectedRows[0].Cells["ruku_tuikuid"].Value);
                        TableRow delRow = new TableRow() { TableName="tbl_tuiku", ID=tuiKuID };
                        if (KeaoUtils._DB.DeleteRowByID(delRow) > 0)
                        {
                            BindInfo();
                        }
                    }
                }
            }
            if (tabControl1.SelectedIndex == 1)
            {
                if (dataGridView2.SelectedRows.Count > 0)
                {
                    if (KeaoUtils.ShowQuestionMessage("确定要删除出库物资退库信息吗？") == DialogResult.Yes)
                    {
                        string tuiKuID = string.Format("{0}", dataGridView2.SelectedRows[0].Cells["chuku_tuikuid"].Value);
                        TableRow delRow = new TableRow() { TableName = "tbl_tuiku", ID = tuiKuID };
                        if (KeaoUtils._DB.DeleteRowByID(delRow) > 0)
                        {
                            BindInfo();
                        }
                    }
                }
            }
        }

        private void menu_2_xiugai_Click(object sender, EventArgs e)
        {
            //修改已完成
            string tuiKuID = string.Empty;
            if (tabControl1.SelectedIndex == 2)
            {
                if (dataGridView3.SelectedRows.Count > 0)
                {
                    tuiKuID = string.Format("{0}", dataGridView3.SelectedRows[0].Cells["ruku_bianhao_yiwancheng"].Value);
                }
            }
            if (tabControl1.SelectedIndex == 3)
            {
                if (dataGridView4.SelectedRows.Count > 0)
                {
                    tuiKuID = string.Format("{0}", dataGridView4.SelectedRows[0].Cells["chuku_bianhao_yiwancheng"].Value);
                }
            }

            if (string.IsNullOrEmpty(tuiKuID))
            {
                return;
            }

            string createCondition = KeaoUtils._DB.CreateAndCondition("id", DataValueCommonType.字符串, tuiKuID, "", SearchConditionType.等于);
            DataTable Dt = KeaoUtils._DB.GetDataTableByCondition("tbl_tuiku", createCondition);
            if (Dt.Rows.Count > 0)
            {
                txt_maozhong.Text = string.Format("{0}", Dt.Rows[0]["tuikumaozhong"]);
                txt_pizhong.Text = string.Format("{0}", Dt.Rows[0]["tuikupizhong"]);
                txt_jingzhong.Text = string.Format("{0}", Dt.Rows[0]["tuikujingzhong"]);
                DataTable wuLiaoDt = cmb_wuliao.DataSource as DataTable;
                foreach (DataRow row in wuLiaoDt.Rows)
                {
                    if (row["wuliaomingcheng"].Equals(Dt.Rows[0]["tuikuwuliao"]) && row["wuliaoleixing"].Equals(Dt.Rows[0]["tuikuleixing"]))
                    {
                        cmb_wuliao.SelectedValue = row["id"];
                    }
                }

                cmb_xinghao.Text = string.Format("{0}", Dt.Rows[0]["tuikuxinghao"]);
                cmb_danweimingcheng.Text = string.Format("{0}", Dt.Rows[0]["tuikudanwei"]);
                txt_beizhu.Text = string.Format("{0}", Dt.Rows[0]["tuikubeizhu"]);
                txt_chepaihao.Text = string.Format("{0}", Dt.Rows[0]["tuikuchepaihao"]);
                m_CurrentID = tuiKuID;
                m_CurrentBianHao = string.Format("{0}", Dt.Rows[0]["tuikubianhao"]);
            }
        }

        private void menu_2_shanchu_Click(object sender, EventArgs e)
        {

            //删除已完成
            if (tabControl1.SelectedIndex == 2)
            {
                if (dataGridView3.SelectedRows.Count > 0)
                {
                    string tuiKuID = string.Format("{0}", dataGridView3.SelectedRows[0].Cells["ruku_bianhao_yiwancheng"].Value);
                    if (string.IsNullOrEmpty(tuiKuID))
                    {
                        return;
                    }

                    if (KeaoUtils.ShowQuestionMessage("确定要删除入库物资退库信息吗？") == DialogResult.Yes)
                    {
                        MainForm.RiZhi(string.Format("{0}删除入库物资退库信息，单号：{1}", KeaoUtils._CurrentUserRow["yonghuxingming"], dataGridView3.SelectedRows[0].Cells["ruku_danhao_yiwancheng"].Value));
                        TableRow delRow = new TableRow() { TableName = "tbl_tuiku", ID = tuiKuID };
                        if (KeaoUtils._DB.DeleteRowByID(delRow) > 0)
                        {
                            BindInfo();
                        }
                    }
                }
            }
            if (tabControl1.SelectedIndex == 3)
            {
                if (dataGridView4.SelectedRows.Count > 0)
                {
                    string tuiKuID = string.Format("{0}", dataGridView4.SelectedRows[0].Cells["chuku_bianhao_yiwancheng"].Value);
                    if (string.IsNullOrEmpty(tuiKuID))
                    {
                        return;
                    }

                    if (KeaoUtils.ShowQuestionMessage("确定要删除出库物资退库信息吗？") == DialogResult.Yes)
                    {
                        MainForm.RiZhi(string.Format("{0}删除出库物资退库信息，单号：{1}", KeaoUtils._CurrentUserRow["yonghuxingming"], dataGridView4.SelectedRows[0].Cells["chuku_danhao_yiwancheng"].Value));
                        TableRow delRow = new TableRow() { TableName = "tbl_tuiku", ID = tuiKuID };
                        if (KeaoUtils._DB.DeleteRowByID(delRow) > 0)
                        {
                            BindInfo();
                        }
                    }
                }
            }
        }

        private SheZhiQuXiang m_SheZhiQuXinag = null;
        private string m_quxiangbiaoduan = string.Empty;
        private void btn_shezhiquxiang_Click(object sender, EventArgs e)
        {
            if (m_SheZhiQuXinag == null)
            {
                m_SheZhiQuXinag = new SheZhiQuXiang();
            }
            if (m_SheZhiQuXinag.ShowDialog() == DialogResult.OK)
            {
                m_quxiangbiaoduan = m_SheZhiQuXinag.m_QuXiangBianHao;
            }
        }
    }
}
